#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui_c.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //cv::VideoCapture capture(0);
    fps = 15;
    video= cv::VideoCapture(0);
    video.set(cv::CAP_PROP_FPS, fps);


    cv::Mat imageTemp;
    video>>imageTemp;
    ShowImage(imageTemp);

    connect(ui->pushButton_start, &QPushButton::clicked, [&]() {
        on_pushButton_play_clicked();
    });

    connect(ui->pushButton_pause, &QPushButton::clicked, [&]() {
    on_pushButton_pause_clicked();
    });

    timer=new QTimer(this);
    ui-> label_image->setScaledContents(true);//可以使图片完全按QWidget缩放，而不保持原视频比例
    connect(timer,SIGNAL(timeout()),this,SLOT(ReadFrame()));
}

void MainWindow::ShowImage(cv::Mat& mat)
{
     //方法二，按比例缩放
    QImage image=MatToQImage2(mat);
    QPixmap pixmap = QPixmap::fromImage(image);
    int width = ui->label_image->width();
    int height = ui->label_image->height();
    QPixmap fitpixmap = pixmap.scaled(width, height, 
                Qt::KeepAspectRatio, Qt::SmoothTransformation);
    //按比例缩放
    ui->label_image->setPixmap(fitpixmap);
}

//图像格式转换
QImage MainWindow::MatToQImage2(const cv::Mat &mat)
{
    QImage img;
    int chana = mat.channels();
    //依据通道数不同，改变不同的装换方式
    if(3 == chana ){
        //调整通道次序
        cv::cvtColor(mat,mat,cv::COLOR_BGR2RGB);
        img = QImage(static_cast<uchar *>(mat.data),mat.cols,mat.rows,QImage::Format_RGB888);
    }
    else if(4 == chana )
    {
        //argb
        img = QImage(static_cast<uchar *>(mat.data),mat.cols,mat.rows,QImage::Format_ARGB32);
    }
    else {
    //单通道，灰度图
    img = QImage( mat.cols, mat.rows , QImage::Format_Indexed8);
    uchar * matdata = mat.data;
        for(int row = 0 ; row <mat.rows ; ++row )
        {
            uchar* rowdata = img.scanLine( row );
            memcpy(rowdata,matdata ,mat.cols);
        matdata+=mat.cols;
        }
    }
    return img;
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_play_clicked()
{
    timer->start(1000/fps);
}

void MainWindow::on_pushButton_pause_clicked()
{
    timer->stop();
}



void MainWindow::ReadFrame()
{

    cv::Mat frame_now;
    video >> frame_now;//读帧进frame
    if (frame_now.empty())
    {
        //QMessageBox::information(this, tr("warning"), tr("the video is end!"));
        timer->stop();

    }
    else {
        ShowImage(frame_now);
    }
}
